package com.jinlejia.erp.ui.house;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.freedom.yefeng.yfrecyclerview.YfListInterface;
import com.freedom.yefeng.yfrecyclerview.YfListMode;
import com.jinlejia.erp.R;
import com.jinlejia.erp.adapter.SearchHistoryAdapter;
import com.jinlejia.erp.adapter.SearchHouseAdapter;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.BaseActivity;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.bean.EstateBean;
import com.jinlejia.erp.bean.SearchHouseHistoryBean;
import com.jinlejia.erp.common.RecycleViewDivider;
import com.jinlejia.erp.databinding.ActivitySearchHouse2Binding;
import com.jinlejia.erp.ui.common.CommonDeleteDialog;
import com.jinlejia.erp.ui.common.ProgressDialog;
import com.jinlejia.erp.utils.DataFilter;
import com.jinlejia.erp.utils.DbUtil;
import com.litesuits.orm.db.assit.QueryBuilder;
import com.litesuits.orm.db.assit.WhereBuilder;
import com.weight.CustomToast;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;

public class SearchHouseActivity2 extends BaseActivity {
    private Context mContext;

    SearchHistoryAdapter historyAdapter;
    SearchHouseAdapter adapter;
    private ProgressDialog progressDialog;

    private ActivitySearchHouse2Binding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_search_house2);

        binding.btBack.setOnClickListener(this::onClick);
        binding.btClear.setOnClickListener(this::onClick);
        binding.tvApply.setOnClickListener(this::onClick);
        mContext = this;
        initView();
    }

    private void initView() {
        progressDialog = new ProgressDialog(this, "请稍等...");
        binding.yfrvSearchResult.setHasFixedSize(true);
        binding.yfrvSearchResult.setLayoutManager(new LinearLayoutManager(this));
        binding.yfrvSearchResult.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.VERTICAL, 2, getResources().getColor(R.color.colorDivider)));
        //region 搜索历史
        ArrayList<SearchHouseHistoryBean> historyList = new ArrayList<>();
        historyList.addAll(DbUtil.getDB(mContext).single().query(SearchHouseHistoryBean.class));
        binding.etSearchText.setHint("请输入楼盘名称");
        Collections.reverse(historyList);
        historyAdapter = new SearchHistoryAdapter(historyList);
        if (historyList.size() > 0)
            historyAdapter.addFooter("清空历史");
        binding.yfrvSearchResult.setAdapter(historyAdapter);
        historyAdapter.setOnFooterViewClickListener(new YfListInterface.OnFooterViewClickListener() {
            @Override
            public void onFooterViewClick(View view, Object o) {

                CommonDeleteDialog dialog = new CommonDeleteDialog(mContext, "清空历史", "确定清空历史记录?");
                dialog.show();
                dialog.setConfirmListener(new CommonDeleteDialog.OnConfirmListener() {
                    @Override
                    public void confirm() {
                        DbUtil.getDB(mContext).single().deleteAll(SearchHouseHistoryBean.class);
                        historyAdapter.getData().clear();
                        historyAdapter.changeMode(YfListMode.MODE_EMPTY);
                    }
                });

            }
        });

        historyAdapter.setOnItemClickListener(new YfListInterface.OnItemClickListener() {
            @Override
            public void onItemClick(View view, Object o) {
                if (o instanceof SearchHouseHistoryBean) {
                    String name = ((SearchHouseHistoryBean) o).getName();
                    String reCode = ((SearchHouseHistoryBean) o).getReCode();
                    String area = ((SearchHouseHistoryBean) o).getArea();
                    String county = ((SearchHouseHistoryBean) o).getCounty();
                    EstateBean bean = new EstateBean();
                    bean.setEstateName(name);
                    bean.setReCode(reCode);
                    bean.setArea(area);
                    bean.setCounty(county);
                    Intent data = new Intent();
                    data.putExtra("data", bean);
                    setResult(RESULT_OK, data);
                }

                finish();
            }
        });
        //endregion

        //region 搜索结果
        ArrayList list = new ArrayList();
        adapter = new SearchHouseAdapter(list, binding.etSearchText.getText().toString());
        adapter.setOnItemClickListener(new YfListInterface.OnItemClickListener() {
            @Override
            public void onItemClick(View view, Object o) {
                if (o instanceof EstateBean) {
                    EstateBean historyBean = (EstateBean) o;
                    Intent data = new Intent();
                    data.putExtra("data", historyBean);
                    setResult(RESULT_OK, data);
                    SearchHouseHistoryBean rshb = new SearchHouseHistoryBean(historyBean.getEstateName(), historyBean.getReCode(),historyBean.getArea(),historyBean.getCounty());
                    ArrayList<SearchHouseHistoryBean> shbList = DbUtil.getDB(mContext).single().query(SearchHouseHistoryBean.class);
                    if (shbList.size() == 20) {
                        //数量达到20，删除第一个
                        DbUtil.getDB(mContext).single().delete(shbList.get(0));
                    }
                    if (DbUtil.getDB(mContext).single().query(new QueryBuilder<>(SearchHouseHistoryBean.class)
                            .whereEquals("reCode", rshb.getReCode())).size() == 0) {
                        //不包含，直接存
                        DbUtil.getDB(mContext).single().save(rshb);
                    } else {
                        //已经存在，先删除再存
                        DbUtil.getDB(mContext).single().delete(WhereBuilder.create(SearchHouseHistoryBean.class, "name=?", new String[]{rshb.getName()}));
                        DbUtil.getDB(mContext).single().save(rshb);
                    }
                }
                finish();
            }
        });
        //endregion

        binding.etSearchText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() > 0) {
                    binding.yfrvSearchResult.setAdapter(adapter);
                    searchData();
                    binding.btClear.setVisibility(View.VISIBLE);
                } else {
                    binding.yfrvSearchResult.setAdapter(historyAdapter);
                    binding.btClear.setVisibility(View.INVISIBLE);
                }
            }
        });

    }

    //region 查询小区列表
    private void searchData() {
        String name = binding.etSearchText.getText().toString();
        MediaType jsonMediaType = MediaType.parse("application/json; charset=utf-8");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("reNameLike", name);
        OkHttpUtils.postString()
                .url(ApiConfig.HOUSE_SOURCE_QUERYE_STATE_LIST)
                .mediaType(jsonMediaType)
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        CustomToast.showToast(mContext, "网络连接失败", 1500);
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(mContext, response)) {
                            JSONObject data = JSON.parseObject(response.get("data").toString());
                            JSONArray list = data.getJSONArray("realEstateList");
                            ArrayList<EstateBean> beans = (ArrayList<EstateBean>) JSON.parseArray(list.toString(), EstateBean.class);
                            //noinspection unchecked
                            adapter.setData(beans);
                            adapter.setWord(binding.etSearchText.getText().toString());
                            binding.yfrvSearchResult.setAdapter(adapter);
                            adapter.notifyDataSetChanged();
                        }
                    }
                });
    }
    //endregion


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_back:
                setResult(RESULT_CANCELED);
                finish();
                break;
            case R.id.bt_clear:
                binding.etSearchText.setText("");
                break;
            case R.id.tvApply:
                Intent intent1 = new Intent(this,ApplyDictActivity.class);
                intent1.putExtra("ishouse",1);
                startActivity(intent1);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        if (null != progressDialog) {
            progressDialog.dismiss();
            progressDialog = null;
        }
        super.onDestroy();
    }
}
